<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-07-20
 * Time: 14:18
 */

namespace app\queue\job;


use app\constant\DistriConst;
use app\constant\OrderConst;
use app\constant\RewardConst;
use app\model\AdminActives;
use app\model\AdminDistridetail;
use app\model\AdminOrder;
use app\model\AdminQueueMessage;
use app\model\AdminReward;
use app\queue\QueueTypes;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\facade\Log;
use think\queue\Job;

class JobActivesUseTimeEnd{

    public function fire(Job $job, $data){

        $model = AdminActives::get($data['id']);
        if($model){
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                $this->failed($data);
                //如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
                $job->delete();
            }else{
                $activeData = $model->getData();
                $cDate = new \DateTime();
                $activeData['end_use_time'];
                $endDate = new \Datetime( $activeData['end_use_time']);
                if($endDate->getTimestamp()<=$cDate->getTimestamp()){
                    //如果已经到了结束时间了
                    try {
                        Db::startTrans();
                        //更新相关未使用的订单状态为已过期
                        $where = ['tid' => $activeData['tid'],
                            'goods_id' => $activeData['id'],
                            'trade_status'=>OrderConst::ORDER_STATUS_NORMAL,
                            'pay_status'=>[OrderConst::PAY_STATUS_PAID_ONLINE,OrderConst::PAY_STATUS_PAID_OFFLINE]
                        ];
                        $result = (new AdminOrder())->where($where)->field('id')->select()->toArray();
                        $ids=[];
                        foreach($result as $item){
                            $ids[]= $item['id'];
                        }
                        (new AdminOrder())->where(['id'=>$ids])->update(['trade_status'=>OrderConst::ORDER_STATUS_EXPIRE]);
                        //更新相关的推广和分销
                        (new AdminReward())->where(['order_id'=>$ids,'tid'=>$activeData['tid']])->update(['status'=>RewardConst::STATUS_CLOSE]);
                        (new AdminDistridetail())->where(['order_id'=>$ids,'tid'=>$activeData['tid']])->update(['status'=>DistriConst::STATUS_CLOSE]);
                        //更新队列记录
                        $done = AdminQueueMessage::done($data['queue_id']);
                        if(!$done){
                            throw new Exception('更新队列记录失败');
                        }
                        Db::commit();
                        $job->delete();
                        return;
                    }catch (Exception $e) {
                        Log::write($e->getMessage() . json_encode($activeData),'error');
                    }
                    Db::rollback();
                }
                //延时2秒执行
                $job->release(2);
            }
        }else{
            $job->delete();
        }
    }

    public function failed($data){

        // ...任务达到最大重试次数后，失败了
        try{
            //添加了失败记录中
            AdminQueueMessage::create(["type" => QueueTypes::ACTIVES_USE_END_TIME, 'level' => 6, 'content' => json_encode($data)]);
        }catch (Exception $e){
            Log::write("操作活动使用截止信息失败，且任务记录失败" . json_encode($data),'error');
        }
    }

}